using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;

/// <summary>
/// 双击文本启用重命名输入框，修改名称后回车或点击外部确认更改
/// </summary>
public class TextRenamer_20250520 : MonoBehaviour, IPointerClickHandler
{
    [Header("UI 组件")]
    public TMP_Text labelText;                   // 显示用的文字标签
    public TMP_InputField inputField;            // 编辑用的输入框

    [Header("双击设置")]
    public float doubleClickThreshold = 0.3f;    // 双击最大间隔秒数

    private float lastClickTime = -1f;           // 上次点击时间

    private void Start()
    {
        ShowLabel(); // 初始只显示文字

        if (inputField != null)
        {
            inputField.onEndEdit.AddListener(OnEndEdit); // 注册回车/失焦事件
        }
    }

    /// <summary>
    /// 捕获点击事件，判断是否为双击
    /// </summary>
    public void OnPointerClick(PointerEventData eventData)
    {
        if (Time.time - lastClickTime < doubleClickThreshold)
        {
            EnterEditMode(); // 双击：进入编辑模式
            lastClickTime = -1f;
        }
        else
        {
            lastClickTime = Time.time; // 单击：记录时间
        }
    }

    /// <summary>
    /// 切换为输入模式
    /// </summary>
    private void EnterEditMode()
    {
        if (labelText == null || inputField == null) return;

        inputField.text = labelText.text;
        inputField.gameObject.SetActive(true);
        labelText.gameObject.SetActive(false);

        EventSystem.current.SetSelectedGameObject(inputField.gameObject);
        inputField.ActivateInputField();
    }

    /// <summary>
    /// 输入结束时更新文字（回车或点击外部）
    /// </summary>
    private void OnEndEdit(string newText)
    {
        if (Input.GetKeyDown(KeyCode.Return) || !inputField.isFocused)
        {
            // 空文本容错
            //if (string.IsNullOrWhiteSpace(newText))
            //{
            //    newText = labelText.text; // 保留原值
            //}

            labelText.text = newText;
            ShowLabel();
        }
    }

    /// <summary>
    /// 恢复显示模式
    /// </summary>
    private void ShowLabel()
    {
        inputField.gameObject.SetActive(false);
        labelText.gameObject.SetActive(true);
    }

    private void Update()
    {
        // 若处于编辑状态，点击任意非输入框区域视为结束编辑
        if (inputField.isActiveAndEnabled && Input.GetMouseButtonDown(0))
        {
            if (!RectTransformUtility.RectangleContainsScreenPoint(
                inputField.GetComponent<RectTransform>(),
                Input.mousePosition,
                Camera.main))
            {
                OnEndEdit(inputField.text);
            }
        }
    }
}
